package com.bilibili.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.bilibili.dubbo.api.mongo.UserLocationApi;
import com.bilibili.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HuangRongFu
 * 2021/11/25 星期四8:45 下午
 */

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 查附近
     * @param userId
     * @param distance
     * @Return: List<Long>
     */
    @Override
    public List<Long> searchNearBy(Long userId, Long distance) {

        List<Long> userIds = new ArrayList<>();
        Query query = new Query(Criteria.where("userId").is(userId));

        UserLocation loginUser = mongoTemplate.findOne(query, UserLocation.class);

        if (null == loginUser){

            return userIds;
        }

        GeoJsonPoint location = loginUser.getLocation();

        Circle circle = new Circle(location, new Distance(distance/1000, Metrics.KILOMETERS));

        Query locationQuery = new Query(Criteria.where("userId").ne(userId).and("location").withinSphere(circle));

        List<UserLocation> userLocations = mongoTemplate.find(locationQuery, UserLocation.class);

        if (CollectionUtil.isNotEmpty(userLocations)){

             userIds = userLocations.stream().map(UserLocation::getUserId).collect(Collectors.toList());

        }

        return userIds;
    }
}
